<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="">
            <el-input
              v-model="foodName"
              size="medium"
              placeholder="查询部门"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              size="small"
              type="success"
              @click="AtomicBoolean"
              icon="el-icon-search"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item label="">
            <el-button
              size="small"
              type="warning"
              @click="notEmpty"
              icon="el-icon-delete-solid"
              >清空</el-button
            >
          </el-form-item>
          <el-form-item label="">
            <el-button
              type="primary"
              size="small"
              @click="addition(1)"
              icon="el-icon-plus"
              >新建</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="24">
        <el-table
          :data="tableData"
          v-loading="loadFlag"
          row-key="id"
          :tree-props="{ children: 'children' }"
          style="width: 100%"
        >
          <el-table-column type="index" width="50" label="序号" align="center">
          </el-table-column>
          <el-table-column prop="departName" label="名称" align="left">
          </el-table-column>
          <el-table-column prop="createTime" label="创建日期" align="center">
          </el-table-column>

          <el-table-column label="操作" width="240" align="center">
            <template #default="scope">
              <el-button size="mini" @click="handleEdit(scope.row, 2)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-dialog
      :title="single"
      v-model="plassets"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="80px">
        <el-form-item label="部门名称" prop="Departmentname">
          <el-input
            v-model="form.Departmentname"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="顶级部门">
          <el-switch v-model="navbar"> </el-switch>
        </el-form-item>
        <el-form-item label="上级部门" v-if="navbar == true">
          <el-cascader
            :show-all-levels="false"
            style="width: 300px"
            clearable
            v-model="superior"
            :options="department"
            :props="{ checkStrictly: true }"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="plassets = false">取 消</el-button>
          <el-button type="primary" v-if="under == 1" @click="Determine('form')"
            >确 定</el-button
          >
          <el-button type="primary" v-else @click="hardware('form')"
            >编辑确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from "dayjs";
export default {
  name: "upload",
  data() {
    return {
      single: "新增部门",
      plassets: false,
      form: {
        Departmentname: "",
      },
      navbar: false, //顶级部门
      foodName: "",
      ofpolice: [],
      superior: "", //上级部门
      tableData: [],
      department: [],
      rules: {
        Departmentname: [
          { required: true, message: "请输入部门名称", trigger: "change" },
        ],
      },
      loadFlag: false, //加载flag
      under: 1,
      underID: "",
      really1: 0,
      headerObj: "", //请求头
    };
  },
  created() {
    let str = sessionStorage.getItem("token");
    this.headerObj = `Bearer ${str}`;
  },
  components: {},
  beforeMount() {
    this.Acquisition();
    this.AtomicBoolean();
  },
  methods: {
    handleEdit(row, index) {
      console.log(row);
      console.log(index);
      this.under = index;
      this.plassets = true;
      this.underID = row.id;
      this.superior = row.pId;
      this.form.Departmentname = row.departName;
    },
    //删除
    handleDelete(row) {
      let into = row;
      this.$confirm("确认删除该设备?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .post(
              `api/serial/Department`,
              {
                id: into.id,
                pId: into.pId,
                departName: into.departName,
                isDelete: 1,
              },
              {
                headers: {
                  Authorization: this.headerObj,
                },
              }
            )
            .then(() => {
              // console.log(res);
              this.AtomicBoolean();
              this.Acquisition();
              this.$message.success("删除成功");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //编辑确定
    hardware(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.navbar == false) {
            this.editors = -1;
          } else {
            if (this.superior.length == 1) {
              this.editors = this.superior[0];
            } else if (this.superior.length == 2) {
              this.editors = this.superior[1];
            } else if (this.superior.length == 3) {
              this.editors = this.superior[2];
            }
          }
          this.$axios
            .post(
              `api/serial/Department`,
              {
                id: this.underID,
                pId: this.superior,
                departName: this.form.Departmentname,
                // departmentList: this.ofpolice,
              },
              {
                headers: {
                  Authorization: this.headerObj,
                },
              }
            )
            .then(() => {
              this.$message({
                message: "保存成功",
                type: "success",
              });
              this.AtomicBoolean();
              this.plassets = false;
            })
            .catch(() => {
              this.$message.error("保存失败");
            });
        } else {
          return false;
        }
      });
    },
    //确定
    Determine(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          console.log(this.superior);
          if (this.navbar == false) {
            this.editors = -1;
          } else {
            if (this.superior.length == 1) {
              this.editors = this.superior[0];
            } else if (this.superior.length == 2) {
              this.editors = this.superior[1];
            } else if (this.superior.length == 3) {
              this.editors = this.superior[2];
            }
          }
          this.$axios
            .post(
              `api/serial/Department`,
              {
                pId: this.editors,
                departName: this.form.Departmentname,
                // departmentList: this.ofpolice,
              },
              {
                headers: {
                  Authorization: this.headerObj,
                },
              }
            )
            .then(() => {
              this.$message({
                message: "保存成功",
                type: "success",
              });
              this.AtomicBoolean();
              this.plassets = false;
            })
            .catch(() => {
              this.$message.error("保存失败");
            });
        } else {
          return false;
        }
      });
    },
    notEmpty() {
      this.foodName = "";
      this.AtomicBoolean();
    },
    AtomicBoolean() {
      this.loadFlag = true;
      this.$axios({
        methods: "GET",
        url: "api/serial/DepartmentTree",
        headers: {
          Authorization: this.headerObj,
        },
        // params: {
        //   pageSize: this.m_page.size,
        //   pageIndex: this.m_page.number,
        // },
      }).then((res) => {
        // ({ data: this.tableData, count: this.m_page.totalElements } = res.data);
        // this.tableData.forEach((item) => {
        //   item.createTime = dayjs(item.createTime).format("YYYY-M-D");
        // });
        this.obtain = res.data.data;
        let mailto = [];
        this.obtain.forEach((item, index) => {
          mailto[index] = {
            createTime: dayjs(item.createTime).format("YYYY-M-D"),
            departName: item.departName,
            id: item.id,
            pId: item.pId,
            updateTime: item.updateTime,
          };
          mailto[index].children = [];
          item.departmentList.forEach((item1, index1) => {
            mailto[index].children[index1] = {
              createTime: dayjs(item1.createTime).format("YYYY-M-D"),
              departName: item1.departName,
              id: item1.id,
              pId: item1.pId,
              updateTime: item1.updateTime,
            };
            mailto[index].children[index1].children = [];
            item1.departmentList.forEach((item2, index2) => {
              mailto[index].children[index1].children[index2] = {
                createTime: dayjs(item2.createTime).format("YYYY-M-D"),
                departName: item2.departName,
                id: item2.id,
                pId: item2.pId,
                updateTime: item2.updateTime,
              };
            });
          });
        });
        this.tableData = mailto;
        console.log(this.tableData);
        this.loadFlag = false;
      });
    },
    handleChange(value) {
      console.log(value);
    },
    addition(index) {
      this.form.Departmentname = "";
      this.under = index;
      this.plassets = true;
    },

    //获取上级部门
    Acquisition() {
      this.$axios
        .get(`api/serial/DepartmentTree`, {
          headers: {
            Authorization: this.headerObj,
          },
        })
        .then((res) => {
          // console.log(res);
          this.fication = res.data.data;
          // console.log(this.fication);
          let arr = [];
          this.fication.forEach((item, index) => {
            console.log(item);
            arr[index] = {
              value: item.id,
              label: item.departName,
            };

            if (item.departmentList) {
              arr[index].children = [];
              item.departmentList.forEach((item1, index1) => {
                arr[index].children[index1] = {
                  value: item1.id,
                  label: item1.departName,
                };
                arr[index].children[index1].children = [];
                item1.departmentList.forEach((item2, index2) => {
                  arr[index].children[index1].children[index2] = {
                    value: item2.id,
                    label: item2.departName,
                  };
                });
              });
            }
          });
          console.log(arr);
          this.department = arr;
        });
    },
  },
};
</script>

<style scoped>
.pagingClass {
  text-align: right;
  height: 40px;
  line-height: 40px;
  /* margin: 20px 0; */
  background-color: #fff;
  margin-bottom: 40px;
}
</style>